<script setup>
// import { ref } from 'vue'
import { storeToRefs } from 'pinia';

// import { ref } from 'vue'
import { useUrl } from '~~/composables/states';
// import { useNaryadList } from '~~/store/naryadlist';
// import { useOneEtap } from '~~/store/naryad';
// import { useNaryadListWaitlist } from '~~/store/naryads_waitlist';
// import { useEtapWaitlist } from '~~/store/naryad_waitlist';

// const it_lab = useNaryadList();
// const it_lab = ref([]);
// const counter = useCounterStore();

const waitlist_naryads = ref([]);

const etap_waitlist = useEtapWaitlist();

const user = useCookie('user');
if (user.value == null) {
    navigateTo('/login');
}
const mpp = useCookie('mpp');

const urlHome = useUrl();

const route = useRouter();
const list_usl = useUslList();
const { usl_list } = storeToRefs(list_usl);
const sort_by = ref('');
const naryad_search = ref('');

const { sort_list } = useSortList();

const modal_number_nar = ref('');
const modal_stu_nar = ref('');
const modal_patient_nar = ref('');

const isOpen = ref(false);

const pend = ref('');
pend.value = false;


const { pending, data: narList, error, refresh: narListUpdate } = await useLazyFetch(`${urlHome.value}lab/nar_list/`, {
    query: {
        mpp: mpp.value,
        status: "waiting"
    }
})


// async function fnWait15sec() {
//     const { data: array_naryad } = useLazyFetch(urlHome.value + 'lab/nar_list' + mpp.value + '&waiting=True', {
//         onRequest({ request, options }) {
//             //set the request headers
//             options.headers = options.headers || {};
//             pend.value = true;
//         },
//         onResponse({ request, response, options }) {
//             waitlist_naryads.value = response._data;
//             pend.value = false;
//             return response._data
//         }
//     })

//     return;
// }
// await fnWait15sec();


async function getUsl(idkv, nkv, stu, fam, im, ot) {
    const { data: usls } = await useAsyncData('usls', () => $fetch(urlHome.value + 'api/pl_uslp/?idkv=' + idkv));
    modal_number_nar.value = nkv;
    modal_stu_nar.value = stu;
    modal_patient_nar.value = fam + ' ' + im + ' ' + ot;
    console.log("usls: ", usls._rawValue);
    list_usl.value = usls._rawValue;
    isOpen.value = true;
    return;
}

function toNaryad(index, id) {
    etap_waitlist.value = waitlist_naryads.value[index];
    console.log("etap_waitlist :", waitlist_naryads.value)
    route.push('/lab/naryad_view/' + id)
    return;
}


function sortNaryadList(sortBy) {
    switch (sortBy) {
        case 'dnaz_etap_inc':
            narList.value.sort(function (a, b) {
                return (new Date(a.dou)) - (new Date(b.dou));
            });
            break;
        case 'dnaz_etap_desc':
            narList.value.sort(function (a, b) {
                return (new Date(b.dou)) - (new Date(a.dou));
            });
            break;
        case 'stu_inc':
            narList.value.sort(function (a, b) {
                return a.stu - b.stu;
            });
            break;
        case 'stu_desc':
            narList.value.sort(function (a, b) {
                return b.stu - a.stu;
            });
            break;
    }
    return;
}

function resetSearch() {
    naryad_search.value = '';
    sort_by.value = '';
    narListUpdate();
}

const refresh = () => refreshNuxtData()

</script>
<style>
.list-complete-item {
    transition: all 0.8s ease;
    display: inline-block;
    margin-right: 10px;
}

.list-complete-enter-from,
.list-complete-leave-to {
    opacity: 0;
    transform: translateY(30px);
}

.list-complete-leave-active {
    position: absolute;
}
</style>

<template>
    <div>
        <div
            class="px-2 py-2 grid grid-cols-2 sm:grid-cols-3 md:grid-cols-3 lg:grid-cols-3 xl:grid-cols-3 2xl:grid-cols-3 sm:flex md:flex lg:flex xl:flex 2xl:flex sm:gap-4">
            <UInput color="green" placeholder="Фамилия пациента" v-model="naryad_search" />
            <USelect color="green" v-model="sort_by" :options="sort_list" option-attribute="name"
                @change="sortNaryadList(sort_by)" />
            <UButton v-if="naryad_search != '' || sort_by != ''" label="Очистить" @click="resetSearch()" />
        </div>

        <div v-if="pend">
            <LoadFetchAnimation></LoadFetchAnimation>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3" v-auto-animate>
            <div v-for="(item, index) in narList" :key="item.nkv">
                <div v-show="item?.patient?.fam.toUpperCase().includes(naryad_search.toUpperCase())">
                    <NaryadListWork>
                        <NaryadListGridOne>
                            <div class="tooltip" data-tip="Открыть наряд">
                                <div class="rounded mx-1 hover:bg-primary" @click="toNaryad(index, item.id)"><b>{{
                item.nkv
            }}</b></div>
                            </div>
                        </NaryadListGridOne>
                        <NaryadListGridTwo>
                            <div v-if="item.id_etap == 1">На распределении</div>
                            <div v-else>{{ item?.user_etap_link?.fam }} {{ item?.user_etap_link?.im[0] }}. {{
                item?.user_etap_link?.ot[0] }}</div>
                        </NaryadListGridTwo>
                        <NaryadListGridOne>{{ ~~((new Date() - new Date(item.dnaz_etap)) / (1000 * 60 * 60 * 24)) }} /
                            {{
                ~~((new Date() - new Date(item.dou)) / (1000 * 60 * 60 * 24)) }}</NaryadListGridOne>
                        <NaryadListGridSeven>{{ item?.patient?.fam }} {{ item?.patient?.im }} {{ item?.patient?.ot }}
                        </NaryadListGridSeven>
                        <NaryadListGridSix>
                            <div class="tooltip" data-tip="Список услуг">
                                <div class="rounded mx-1 hover:bg-primary"
                                    @click="getUsl(item?.idkv, item?.nkv, item?.stu.toLocaleString(), item?.patient?.fam, item?.patient?.im, item?.patient?.ot)">
                                    <b>{{ item && item.stu ? item.stu.toLocaleString() : "" }} ₽</b>
                                </div>
                            </div>
                        </NaryadListGridSix>
                    </NaryadListWork>
                </div>
            </div>
        </div>
        <UModal v-model="isOpen">
            <UCard :ui="{ divide: 'divide-y divide-gray-100 dark:divide-gray-800' }">
                <template #header>
                    <div
                        class="grid grid-cols-1 sm:grid-cols-3 md:grid-cols-3 lg:grid-cols-3 xl:grid-cols-3 2xl:grid-cols-3 sm:flex md:flex lg:flex xl:flex 2xl:flex sm:gap-4">
                        <div class="text-2xl ">Наряд : <b>{{ modal_number_nar }}</b></div>
                        <div class="text-2xl ">Сумма : <b>{{ modal_stu_nar }} ₽</b></div>
                        <div class="text-1xl align-middle">Пациент : {{ modal_patient_nar }}</div>
                    </div>
                </template>
                <div class="overflow-x-auto relative">
                    <div class="flex flex-row w-full">
                        <div class="basis-1/4"><b>Код</b></div>
                        <div class="basis-1/4"><b>Кол-во</b></div>
                        <div class="basis-1/4"><b>Цена</b></div>
                        <div class="basis-1/4"><b>Сумма</b></div>
                    </div>
                    <hr>
                    <div v-for="(item, index) in list_usl.value" :key="item.kusl">
                        <div v-if="index % 2 == 0" class="">
                            <div class="flex flex-row w-full">
                                <div class="basis-1/4"><b>{{ item.kusl }}</b></div>
                                <div class="basis-1/4"><b>{{ item.kol }}</b></div>
                                <div class="basis-1/4"><b>{{ (item.price).toLocaleString() }} ₽</b></div>
                                <div class="basis-1/4"><b>{{ (item.stu).toLocaleString() }} ₽</b></div>
                            </div>

                            <div class="break-words">{{ item.nusl }}</div>
                        </div>
                        <div v-else>
                            <div class="flex flex-row w-full">
                                <div class="basis-1/4"><b>{{ item.kusl }}</b></div>
                                <div class="basis-1/4"><b>{{ item.kol }}</b></div>
                                <div class="basis-1/4"><b>{{ (item.price).toLocaleString() }} ₽</b></div>
                                <div class="basis-1/4"><b>{{ (item.stu).toLocaleString() }} ₽</b></div>
                            </div>
                            <div class="break-words">{{ item.nusl }}</div>
                        </div>
                        <hr>
                    </div>
                </div>
                <template #footer>
                    <UButton label="Закрыть" @click="isOpen = false" />
                </template>
            </UCard>
        </UModal>
    </div>
</template>